<template>
  <div class="container">
    <el-tabs v-model="activeTab" class="tabs" @tab-click="handleTabClick">
      <el-tab-pane label="酸轧TCM2280" name="tcm2280" />
      <el-tab-pane label="连退CAL2150" name="cal2150" />
      <el-tab-pane label="连退CAL1630" name="cal1630" />
      <el-tab-pane label="镀锌CGL1870" name="cgl1870" />
    </el-tabs>
    <el-container>
      <el-header>
        <el-form :model="searchHeader" label-width="auto" class="header-search-form">
          <el-form-item label="开始时间" class="time-period-picker">
            <el-date-picker
              v-model="searchHeader.startDate"
              type="datetime"
              placeholder="开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :editable="false"
              style="width: 13rem"
            />
          </el-form-item>
          <el-form-item label="结束时间" class="time-period-picker">
            <el-date-picker
              v-model="searchHeader.endDate"
              type="datetime"
              placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :editable="false"
              style="width: 13rem"
            />
          </el-form-item>
          <el-form-item label="下限">
            <el-input v-model="searchHeader.lowerLimit" style="width: 6rem" />
          </el-form-item>
          <el-form-item label="上限">
            <el-input v-model="searchHeader.upperLimit" style="width: 6rem" />
          </el-form-item>
          <el-form-item label="控制目标">
            <el-input v-model="searchHeader.controlTarget" style="width: 10rem" />
          </el-form-item>
          <el-form-item label="参数">
            <el-select v-model="searchHeader.param" clearable style="width: 10rem">
              <el-option label="全部" value="" />
              <el-option label="备选1" value="备选1" />
              <el-option label="备选2" value="备选2" />
              <el-option label="备选3" value="备选3" />
            </el-select>
          </el-form-item>
          <el-form-item label="样品名称">
            <el-select v-model="searchHeader.sampleName" clearable style="width: 10rem">
              <el-option label="全部" value="" />
              <el-option label="备选1" value="备选1" />
              <el-option label="备选2" value="备选2" />
              <el-option label="备选3" value="备选3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-container>
        <el-aside class="aside-container">
          <div class="coild-list">
            <!-- 卷号列表 
              @row-click="coildListClick"-->
            <el-table
              :data="coildList"
              max-height="85vh"
              class="data-table"
              :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
              :cell-style="{ color: '#fff', textAlign: 'center' }"
              v-loading="isLoading"
              element-loading-text="加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="transparent"
              ref="tableRef"
            >
              <el-table-column prop="serialNumber" label="序号" width="60" />
              <el-table-column prop="dialNumber" label="卷号" />
              <template #empty>
                <div style="color: #fff; text-align: center; padding: 20px">暂无数据</div>
              </template>
            </el-table>
          </div>
        </el-aside>
        <el-main>
          <div
            class="quad-grid"
            v-loading="isLoading"
            element-loading-text="加载中..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="transparent"
          >
            <div class="grid-content">
              <graph-line
                :data1="graphData.singleValue"
                :datax="Array.from({ length: graphData.singleValue.length || 0 }, (_, i) => i + 1)"
                :data-name="['单值']"
                :mark-line="30"
              ></graph-line>
            </div>
            <div class="grid-content">
              <graph-bar-line
                :data-bar="graphData.histogramBar"
                :data-line="graphData.histogramLine"
                :datax="Array.from({ length: graphData.histogramLine.length || 0 }, (_, i) => i + 1)"
                :data-name="['', '']"
              ></graph-bar-line>
            </div>
            <div class="grid-content">
              <graph-line
                :data1="graphData.singleValue"
                :datax="Array.from({ length: graphData.singleValue.length || 0 }, (_, i) => i + 1)"
                :data-name="['移动极差']"
              ></graph-line>
            </div>
            <div class="grid-content">
              <el-tabs v-model="cpk" class="cpk-container">
                <el-tab-pane label="过程能力指数" name="cpk">
                  <el-form :model="cpkForm" class="cpk-form" label-width="auto">
                    <el-form-item v-for="(value, key, index) in cpkForm" :key="key as string" :label="`CPK${index + 1}`">
                      <el-input v-model="cpkForm[key as keyof typeof cpkForm]" style="width: 8rem" />
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElMessage, ElNotification } from 'element-plus';
  import type { TabsPaneContext, ElTable } from 'element-plus';
  import { debounce } from 'lodash-es';
  import { useUserStore } from '/@/store/modules/system/user';
  import GraphLine from './components/GraphLine.vue';
  import GraphBarLine from './components/GraphBarLine.vue';
  import { spcApi } from '/@/api/spcProcessCapabilityMonitor';

  const data = ref([{ menuName: 'SPCIndex', menuTitle: 'SPC过程能力监控', menuId: '1' }]);
  onBeforeMount(() => {
    useUserStore().setTagNav(data.value);
  });

  interface SearchForm {
    prodLine: string;
    startDate: string;
    endDate: string;
    lowerLimit: string;
    upperLimit: string;
    controlTarget: string;
    param: string;
    sampleName: string;
  }

  const isLoading = ref(false);
  const activeTab = ref('tcm2280');
  type CoildRow = { serialNumber: number; dialNumber: string };
  const coildList = ref<CoildRow[]>([]);
  const errList = ref<string[]>([]);
  // TODO 后续替换为真实数据
  const singleValue = ref([
    3, 49, 48, 47, 5, 50, 1, 45, 8, 43, 6, 48, 4, 40, 46, 42, 47, 46, 7, 41, 15, 35, 5, 44, 2, 50, 10, 33, 1, 49, 14, 28, 3, 47, 18, 22, 6, 45, 20,
    15, 8, 43, 25, 10, 5, 40, 28, 7, 3, 38, 30, 5, 2, 35, 32, 4, 1, 33,
  ]);
  const histogramBar = ref([48, 210, 325, 180, 75, 260, 340, 195, 120, 15]);
  const histogramLine = ref([0.002, 0.0054, 0.0115, 0.0189, 0.0243, 0.0243, 0.0189, 0.0115, 0.0054, 0.002]);
  const cpk = ref('cpk');
  const graphData = reactive({
    singleValue: singleValue.value,
    histogramBar: histogramBar.value,
    histogramLine: histogramLine.value,
  });
  // 过程能力指数表单
  const cpkForm = reactive({
    cpk1: 0,
    cpk2: 0,
    cpk3: 0,
    cpk4: 0,
    cpk5: 0,
    cpk6: 0,
    cpk7: 0,
    cpk8: 0,
    cpk9: 0,
    cpk10: 0,
    cpk11: 0,
    cpk12: 0,
    cpk13: 0,
    cpk14: 0,
  });
  // 搜索头
  const searchHeader = reactive<SearchForm>({
    prodLine: activeTab.value,
    startDate: '',
    endDate: '',
    lowerLimit: '',
    upperLimit: '',
    controlTarget: '',
    param: '',
    sampleName: '',
  });
  // 切换产线
  const handleTabClick = (tab: TabsPaneContext, event: Event) => {
    const name = String(tab.paneName ?? '');
    activeTab.value = name;
    searchHeader.prodLine = name;
    debouncedFetchData();
  };

  // 查询按钮
  const handleSearch = () => {
    debouncedFetchData();
  };
  // 重置方法
  const handleReset = async () => {
    (Object.keys(searchHeader) as Array<keyof SearchForm>).forEach((key) => {
      searchHeader[key] = '';
    });
    handleSearch();
  };

  // 防抖查询函数
  const debouncedFetchData = debounce(async () => {
    if (isLoading.value) return;
    await fetchData();
  }, 300);

  const fetchData = async () => {
    if (isLoading.value) return;
    isLoading.value = true;
    errList.value = [];
    try {
      await Promise.all([getCoildList(), getGraphData()]);

      if (errList.value.length > 0) {
        ElNotification({
          title: 'Error',
          message: errList.value.join('<br>'),
          type: 'error',
          dangerouslyUseHTMLString: true,
        });
      } else {
        ElMessage.success('查询成功');
      }
    } catch (error) {
      console.error('数据获取失败:', error);
      ElMessage.error('数据获取失败');
    } finally {
      isLoading.value = false;
    }
  };
  const getCoildList = async () => {
    try {
      const param = { ...searchHeader };
      console.log(coildList.value.length);
      // TODO 实现真实接口
      if (coildList.value.length === 0) {
        const rows: CoildRow[] = [];
        for (let i = 1; i <= 200; i += 1) {
          // 模拟卷号：58831 + 两位区段 + 5 个 0（与截图风格相近）
          const mid = String((i % 90) + 10).padStart(2, '0');
          const dial = `58831${mid}00000`;
          rows.push({ serialNumber: i, dialNumber: dial });
        }
        coildList.value = rows;
      }
    } catch (err: any) {
      const errorInfo = {
        message: '获取卷号数据失败',
        error: err instanceof Error ? err.message : String(err),
        timestamp: new Date().toISOString(),
      };
      console.error('API Error:', errorInfo);
      errList.value.push(errorInfo.message);
    }
  };

  const getGraphData = async () => {
    const param = { ...searchHeader };
    try {
      // TODO 实现真实接口
      graphData.singleValue = singleValue.value;
      graphData.histogramBar = histogramBar.value;
      graphData.histogramLine = histogramLine.value;
    } catch (err: any) {
      const errorInfo = {
        message: '获取图表数据失败',
        error: err instanceof Error ? err.message : String(err),
        timestamp: new Date().toISOString(),
      };
      console.error('API Error:', errorInfo);
      errList.value.push(errorInfo.message);
    }
  };

  onMounted(() => {
    fetchData();
  });

  onUnmounted(() => {});
</script>
<style scoped lang="less">
  .container {
    // width: 100%;
    min-height: 100vh;
    padding: 0.5%;
    border-radius: 8px;
    background: url(/@/assets/images/home/body-bg.jpg) no-repeat;
  }

  .header-search-form {
    display: flex;
    flex: 1;
    gap: 1rem;
    padding: 12px;
  }

  .aside-container {
    padding: 20px;
  }

  .quad-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, minmax(20vh, 1fr));
    gap: 12px;
    min-height: 80vh;
  }

  .grid-content {
    position: relative;
    background: rgba(7, 23, 55, 0.35);
    border: 1px solid transparent;
    border-radius: 8px;
    padding: 12px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-image: linear-gradient(135deg, #0072ff, #00eaff, #01aaff) 1;
    box-shadow:
      inset 0 0 12px rgba(0, 234, 255, 0.12),
      0 0 10px rgba(0, 114, 255, 0.2);
    transition:
      box-shadow 0.25s ease,
      transform 0.15s ease;

    &:hover {
      box-shadow:
        inset 0 0 16px rgba(0, 234, 255, 0.18),
        0 0 16px rgba(0, 114, 255, 0.35);
      transform: translateY(-1px);
    }
  }

  .cpk-container {
    width: 100%;
  }

  /* CPK 表单两列均分布局 */
  .cpk-form {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
  }
  .cpk-form :deep(.el-form-item) {
    margin-bottom: 0;
  }

  // ------------------------------------------------------------ element-plus样式深度穿透 -------------------------------------------

  :deep(.el-form-item__label) {
    color: #fff !important;
  }

  :deep(.el-table) {
    background-color: transparent !important;
    --el-table-border: none;
    --el-table-row-hover-bg-color: unset;
    color: white;
  }

  :deep(.el-table th),
  :deep(.el-table tr),
  :deep(.el-table td) {
    background-color: transparent;
  }

  :deep(.el-table__row:nth-child(odd)) {
    background-color: #223671;
  }

  :deep(.el-table__inner-wrapper::before) {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0;
  }

  .time-period-picker :deep(.el-input__wrapper) {
    background-color: transparent !important;
  }

  .time-period-picker :deep(.el-input__inner) {
    color: #fff;
  }

  .time-period-picker :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 0.06rem rgba(255, 255, 255, 0.9) inset;
  }

  .time-period-picker :deep(.el-input__prefix) {
    color: #fff;
  }

  :deep(.el-input__inner) {
    color: #fff;
  }

  .select :deep(.el-select__inner) {
    color: #fff;
  }

  .select :deep(.el-select__selected-item) {
    color: #fff;
  }

  :deep(.el-input__wrapper) {
    background: linear-gradient(90deg, #0b3571, rgba(11, 53, 113, 0) 100%);
    box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  }

  :deep(.el-select__wrapper) {
    background: linear-gradient(90deg, #0b3571, rgba(11, 53, 113, 0) 100%);
    box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  }

  :deep(.el-select:hover:not(.el-select--disabled) .el-input__wrapper) {
    box-shadow: 0 0 0 0 var(--el-select-input-focus-border-color) inset !important;
  }

  :deep(.el-select .el-input.is-focus .el-input__wrapper) {
    box-shadow: 0 0 0 0 var(--el-select-input-focus-border-color) inset !important;
  }

  :deep(.el-select:hover:not(.el-select--disabled) .el-input__wrapper) {
    background: #0b3571;
  }

  :deep(.el-select .el-input__wrapper) {
    background: #0b3571;
  }

  .header-search-form :deep(.el-input__inner) {
    color: #fff;
  }

  .tabs {
    :deep(.el-tabs) {
      &__item:not(.is-active) {
        color: #ccc !important;
      }
    }
  }
</style>
